import numpy as np
import time





def logistic_map(x, r):
    return r * x * (1 - x)



#生成混沌序列
def generate_chaotic_sequence(size, r, x0):
    sequence = []
    x = x0
    for _ in range(size):
        x = logistic_map(x, r)
        sequence.append(x)
    return np.array(sequence)






# 加密图像中掩模外的区域
def encrypt_region(image, mask, key_sequence):
    time_start = time.time()
    height, width, channels = image.shape

    # 扁平化图像数据和mask
    flat_image = image.flatten()
    flat_mask = mask.flatten()

    # 创建加密图像
    encrypted_image = flat_image.copy()

    # 找到非人脸区域
    mask_flat = (flat_mask == 255)  # 选择非人脸区域
    print(f"mask_flat shape: {mask_flat.shape}, key_sequence length: {len(key_sequence)}")

    # 检查是否有非人脸区域，并且确保混沌序列长度足够
    non_face_pixel_count = np.sum(mask_flat)
    if non_face_pixel_count > 0:
        if len(key_sequence) < non_face_pixel_count:
            raise ValueError("混沌序列长度不足，无法加密非人脸区域")

        # 使用 NumPy 向量化操作进行加密
        encrypted_image[mask_flat] = np.bitwise_xor(flat_image[mask_flat],
                                                    (key_sequence[:non_face_pixel_count] * 255).astype(np.uint8))
    else:
        print("没有找到非人脸区域，无法进行加密。")

    time_end = time.time()
    print(f"加密一帧用时{time_end - time_start}s")

    return encrypted_image.reshape((height, width, channels))
